package com.xy.ddd.core.convertor;

import com.xy.ddd.core.model.DomainModel;
import com.xy.ddd.core.po.BasePo;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractConvertor<D extends DomainModel, P extends BasePo> implements IConvertor<D, P>{
    /**
     * @param poList 数据库映射实体类
     * @return
     */
    @Override
    public List<D> convert2ModelList(List<P> poList) {
        if (CollectionUtils.isEmpty(poList)) {
            return new ArrayList<>();
        }
        List<D> list = poList.stream().map(po -> convert(po)).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<P> convert2PoList(List<D> modelList) {
        if (CollectionUtils.isEmpty(modelList)) {
            return new ArrayList<P>();
        }
        List<P> list = modelList.stream().map(model -> convert(model)).collect(Collectors.toList());
        return list;
    }

    public Class<D> getDomainModelClass() {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            return (Class)((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        }
        throw new IllegalStateException("未定转换器泛型");
    }

    public Class<P> getPoClass() {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            return (Class)((ParameterizedType) genericSuperclass).getActualTypeArguments()[1];
        }
        throw new IllegalStateException("未定转换器泛型");
    }
}
